package com.wk.springboot.httpUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @Classname DrspHttpResponse
 * @Description DrspHttpResponse
 * @Date 2020/8/7 11:15
 * @Author by weikai
 */
public class DrspHttpResponse {

    
    private static Logger LOG = LoggerFactory.getLogger(DrspHttpResponse.class);
    
    
    private CloseableHttpResponse response;

    /**
     * 默认字符集
     */
    private static String CHARSET_UTF8_STR = "UTF-8";

    /**
     * 默认字符集
     */
    private static Charset CHARSET_UTF8 = Charset.forName(CHARSET_UTF8_STR);

    public DrspHttpResponse(CloseableHttpResponse response) {
        this.response = response;
    }

    /**
     * 读取文本响应
     * @param response
     * @return
     * @throws ParseException 
     * @throws IOException
     */
    public String getText() throws ParseException, IOException {
        HttpEntity httpEntity = this.response.getEntity();
        return EntityUtils.toString(httpEntity, CHARSET_UTF8);
    }

    /**
     * 获取文件流
     * @param response
     * @return
     * @throws UnsupportedOperationException
     * @throws IOException
     */
    public InputStream getStream() throws UnsupportedOperationException, IOException {
        HttpEntity httpEntity = this.response.getEntity();
        return httpEntity.getContent();
    }

    /**
     * 返回http调用状态码
     * @return
     */
    public int getStatusCode() {
        return this.response.getStatusLine().getStatusCode();
    }
    
    
    /**
     * 关闭响应
     * @param response
     * @throws DrspHttpException
     */
    public void closeResponse() throws DrspHttpException {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                String errorMessage = "未知异常";
                LOG.error(errorMessage);
                throw new DrspHttpException(errorMessage, e);
            }
        }
    }

}
